﻿module Sustainalytics.Notifications.Admin {
    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;
    import Routing = Sustainalytics.Routing;

    export class NotificationAddEditController {

        // controller scope
        public $scope: ng.IScope;
        // services
        private $q: ng.IQService;
        private $location: ng.ILocationService;
        private $routeParams: any;
        private RoutingService: Routing.IRoutingService;
        private notificationFactory: Common.INotificationFactory;
        private notificationsService: NotificationsService;
        private staticObjectsAdmin: CommonAdmin.IStaticObjects;
        private asyncSaveOperation: Sustainalytics.Common.AsyncHttpOperation<any>;
        private asyncLoadOperation: Sustainalytics.Common.AsyncHttpOperation<any>;
        private notificationsStatusesService: NotificationsStatusesService;

        // specifies whether current controller is in loading state
        //public isLoading: boolean;
        public currentNotification: NotificationDto;
        //public submitted: boolean;
        public currentStatusDescription: string;
        public isPublished: boolean;

        public errors: any;
        private validationErrors =
        {
            ///add all server validation codes and related ui field.
            0: { field: "name", message: "validation message." }
        };

        private serverErrors = {
            validationError: 1
        }

        constructor(
            $scope: ng.IScope,
            $q: ng.IQService,
            $location: ng.ILocationService,
            RoutingService: Routing.IRoutingService,
            notificationFactory: Common.INotificationFactory,
            staticObjectsAdmin: CommonAdmin.IStaticObjects,
            NotificationsService,
            NotificationsStatusesService) {

            var ctx = this;

            ctx.$scope = $scope;
            ctx.$q = $q;
            ctx.$location = $location;

            ctx.notificationFactory = notificationFactory;
            ctx.staticObjectsAdmin = staticObjectsAdmin;
            ctx.$routeParams = RoutingService.getRouteParams();

            ctx.notificationsService = NotificationsService;
            ctx.notificationsStatusesService = NotificationsStatusesService;

            ctx.asyncSaveOperation = new Sustainalytics.Common.AsyncHttpOperation();
            ctx.asyncLoadOperation = new Sustainalytics.Common.AsyncHttpOperation();

            // load all required data
            ctx.load();

            // scope
            $scope['notificationAddEdit'] = ctx;
            $scope.$emit('notificationAddEdit.created', ctx);

        }

        private load(): void {
            var ctx = this;

            var def = ctx.$q.defer();

            this.currentStatusDescription = "Undefined";
            this.isPublished = true;

            var getNotificationPromise: ng.IPromise<NotificationDto> = ctx.notificationsService.getNotification();

            getNotificationPromise.then(
                // success
                (response: NotificationDto) => {
                    console.log(response);
                    this.currentNotification = response;

                    if (response.status === ctx.notificationsStatusesService.statuses.Published.id ) {
                        this.currentStatusDescription = ctx.notificationsStatusesService.statuses.Published.name;
                        this.isPublished = true;
                    }

                    if (response.status === ctx.notificationsStatusesService.statuses.Unpublished.id) {
                        this.currentStatusDescription = ctx.notificationsStatusesService.statuses.Unpublished.name;
                        this.isPublished = false;
                    }
                },
                // error
                () => {
                    def.reject();
                });
        }

        public cancel(confirmed: boolean) {
            var ctx = this;

            if (!confirmed) {
                if (!confirm('Are you sure you want to leave this page?')) {
                    return;
                }
            }
            // notify operation cancelled
            ctx.$location.path('/notifications');
        }

        public publish() {
            var ctx = this;
            ctx.save(ctx.notificationsStatusesService.statuses.Published.id);

            ctx.currentStatusDescription = ctx.notificationsStatusesService.statuses.Published.name;
            ctx.isPublished = true;
        }

        public unpublish() {
            var ctx = this;
            ctx.save(ctx.notificationsStatusesService.statuses.Unpublished.id);

            ctx.currentStatusDescription = ctx.notificationsStatusesService.statuses.Unpublished.name;
            ctx.isPublished = false;
        }

        private save(status: number): void {

            var ctx = this;

            if (ctx.currentNotification.body) {
                var newText = $("#notificationSummary").text().replace("H1H2H3Toggle HTML", "");
                newText = newText.replace("\n", "");
                newText = newText.trim();

                if (newText.length == 0) {
                    ctx.$scope['form']["body"].$setValidity("required", false);
                }
            }

            if (ctx.$scope['form'].$invalid) {
                ctx.notificationFactory.error('', 'Please correct all errors before saving.');
                return;
            }

            if (ctx.asyncSaveOperation.executing) {
                ctx.notificationFactory.error('Operation in progress.', 'Please wait for previous save operation to complete.');
                return;
            }


            var saveOperation = function () {
                    return ctx.notificationsService.updateNotification(ctx.currentNotification);
            }

            ctx.currentNotification.status = status;
            ctx.asyncSaveOperation.execute(saveOperation).then(
                (response: ng.IHttpPromiseCallbackArg<any>) => {
                    ctx.currentNotification = response.data;
                    ctx.notificationFactory.success("Save operation executed successfully.");
                    ctx.cancel(true);
                },
                (response: ng.IHttpPromiseCallbackArg<Common.IErrorDto<any>>) => {
                    if (response && response.data && response.data.errorStatusCode === ctx.serverErrors.validationError) {
                        ctx.notificationFactory.error("Validation failed", "Client and Server version are not incompatible.");
                        return;
                    }

                    var message = ctx.staticObjectsAdmin.getErrorMesageByStatusCode(response.status, response.data);
                    ctx.notificationFactory.error("Error", message);
                    return;
                });
        }
    }

    var mod = angular.module(notificationsAdminModuleName);

    mod.controller('NotificationAddEditController',
        ['$scope', '$q', '$location', 'RoutingService', 'notificationFactory', 'staticObjectsAdmin', 'NotificationsService', 'NotificationsStatusesService', NotificationAddEditController]);
}